package com.gzdh.dishrecognition.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.iot.bpaas.api.BPaaSApi;
import com.alipay.iot.bpaas.api.service.BPaaSCallback;
import com.alipay.iot.bpaas.api.service.BPaaSResponse;
import com.alipay.iot.bpaas.api.service.LocalService;
import com.alipay.iot.sdk.APIManager;
import com.alipay.iot.sdk.payment.PaymentAPI;
import com.alipay.zoloz.smile2pay.verify.Smile2PayResponse;
import com.blankj.utilcode.util.StringUtils;
import com.dhkj.web.utils.MyObserverRes;
import com.dhkj.web.utils.RequestUtils;
import com.greendao.dao.FkEntityDao;
import com.greendao.dao.OrdersDetailsEntityDao;
import com.greendao.dao.OrdersEntityDao;
import com.gzdh.dishrecognition.AppContext;
import com.gzdh.dishrecognition.MainActivity;
import com.gzdh.dishrecognition.R;
import com.gzdh.dishrecognition.ali.AliRead;
import com.gzdh.dishrecognition.config.ProductConst;
import com.gzdh.dishrecognition.config.SysConstConfig;
import com.gzdh.dishrecognition.config.SystemConfig;
import com.gzdh.dishrecognition.emu.DeviceTypeEmus;
import com.gzdh.dishrecognition.emu.ModelEmus;
import com.gzdh.dishrecognition.emu.OfflineGetCardSnTypeEmus;
import com.gzdh.dishrecognition.emu.PeripheralDeviceEmus;
import com.gzdh.dishrecognition.emu.ReadCardTypeEmus;
import com.gzdh.dishrecognition.entity.FkEntity;
import com.gzdh.dishrecognition.entity.OrdersDetailsEntity;
import com.gzdh.dishrecognition.entity.OrdersEntity;
import com.gzdh.dishrecognition.event.CartEvent;
import com.gzdh.dishrecognition.model.PayModel;
import com.gzdh.dishrecognition.model.ProductCartModel;
import com.gzdh.dishrecognition.ui.adapter.defaultview.DefaultCartPreAdapter;
import com.gzdh.dishrecognition.ui.base.BaseMVCActivity;
import com.gzdh.dishrecognition.ui.dialog.PayingDialog;
import com.gzdh.dishrecognition.ui.pre.SelectPayPre;
import com.gzdh.dishrecognition.util.ByteUtil;
import com.gzdh.dishrecognition.util.KeyAdd;
import com.gzdh.dishrecognition.util.ScanKeyManager;
import com.gzdh.dishrecognition.util.SystemUtils;
import com.gzdh.dishrecognition.util.print.PrintUtil;
import com.jiebao.nfc.uartnfc.CardReaderDevice;
import com.jiebao.util.CardReaderUtils;
import com.serialport.JBScanner;
import com.serialport.OnDecodeCallback;
import com.yzy.voice.VoicePlay;

import net.posprinter.posprinterface.TaskCallback;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.disposables.Disposable;

public class SelectPayActivity extends BaseMVCActivity {
    private static final String TAG = "OfflineResultActivity";

    private int closeSec = 60;

    private RecyclerView cartRv;

    private TextView tv_price;

    private Context mContext;

    private DefaultCartPreAdapter defaultCartAdapter;

    private SelectPayPre selectPayPre;

    Disposable mdDisposable;

    private TextView preCloseTv;

    private TextView tv_close_time;

    private TextView stateTv;

    private TextView cardNoTv;
    private TextView nameTv;
    private TextView btyeTv;
    private TextView kyeTv;

    private View closeText;
    private LinearLayout cardInfoLinear;
    private FkEntityDao fkEntityDao;
    private OrdersDetailsEntityDao ordersDetailsEntityDao;
    private OrdersEntityDao ordersEntityDao;
    private JBScanner scanner = null;
    private ScanKeyManager scanKeyManager;

    private String mSessionId = "";
    private String mTradeNo = "";
    private String ftoken = "";

    private String orders = "";

    private int payStatus = 0;

    private boolean running = true;
    private TextView cashPayBut;

    private TextView cancelBut;

    public static void startAct(Context context) {
        Intent intent = new Intent(context, SelectPayActivity.class);
        context.startActivity(intent);
    }

    PayingDialog payingDialog;
    private AliRead aliRead = new AliRead();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_select_pay;
    }

    @Override
    protected void initView() {
        payStatus = 0;
        String pos = SysConstConfig.getInstance().getPos();
        orders = "ICZF" + pos + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        mContext = this;
        payingDialog = new PayingDialog(mContext);
        switch (SysConstConfig.getInstance().getPeripheralDeviceModel()) {
            case defaultType:
                if (SysConstConfig.getInstance().getDeviceType() != 2) {
                    scanner = new JBScanner(callback);
                    scanner.startScan();
                }

                break;
            case cloudQrAndReadCard:
                startKeyScan();
                break;
        }
        startKeyScan();
        fkEntityDao = AppContext.getInstance().getDaoSession().getFkEntityDao();
        ordersDetailsEntityDao = AppContext.getInstance().getDaoSession().getOrdersDetailsEntityDao();
        ordersEntityDao = AppContext.getInstance().getDaoSession().getOrdersEntityDao();
        cartRv = findViewById(R.id.cartRv);
        tv_price = findViewById(R.id.tv_price);
        cardNoTv = findViewById(R.id.cardNoTv);
        nameTv = findViewById(R.id.nameTv);
        nameTv.setVisibility(View.GONE);
        btyeTv = findViewById(R.id.btyeTv);
        kyeTv = findViewById(R.id.kyeTv);
        cardInfoLinear = findViewById(R.id.cardInfoLinear);
        findViewById(R.id.backBut).setOnClickListener(view -> finish());
        stateTv = findViewById(R.id.stateTv);
        tv_close_time = findViewById(R.id.tv_close_time);
        closeText = findViewById(R.id.closeText);
        if(SysConstConfig.getInstance().getSurfaceModel() == ModelEmus.fixedType) {
            closeText.setVisibility(View.GONE);
        } else {
            closeText.setVisibility(View.VISIBLE);
        }
        if (SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.ali || SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.jeBaoAli) {
            closeSec = 25;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("tradeAmount", ProductConst.getInstance().getProductCartPrice());

            Bundle bundle = new Bundle();
            bundle.putString("templateId", SystemConfig.getInstance().getTemplateId());
            bundle.putString("operateType", "startVerify");
            bundle.putString("page", "faceVerify");
            bundle.putString("templateParams", jsonObject.toJSONString());

            BPaaSApi.getInstance().startBPaaSService(SystemConfig.getInstance().getAbcpApplicationAppid(),
                    SystemConfig.getInstance().getTemplateServiceCode(), bundle, new BPaaSCallback() {
                        @Override
                        public void onResponse(BPaaSResponse response) {
                            if (response == null) {
                                Log.e(TAG, "response is null");
                                return;
                            }
                            if (response.getCode() == BPaaSResponse.RESULT_CODE_FAIL) {
                                String subCode = response.getSubCode();
                                String subMsg = response.getSubMsg();
                                // bpaas服务调用失败
                                Log.e(TAG, "bpaas transfer fail subCode = " + subCode + ",subMsg = " + subMsg);
                            } else if (response.getCode() == BPaaSResponse.RESULT_CODE_SUCCESS) {
                                Log.i(TAG, "onResponse :" + response);
                                if (response.getResult() != null) {
                                    Bundle result = response.getResult().getBundle(LocalService.KEY_LOCAL_RESULT);
                                    if (result != null) {
                                        int code = result.getInt("code");
                                        Log.i(TAG, "code:" + code);
                                        Bundle extInfo = result.getBundle("extInfo");
                                        if (extInfo != null) {
                                            String resultStr = extInfo.getString("result");
                                            if (!TextUtils.isEmpty(resultStr)) {
                                                JSONObject extJson = JSONObject.parseObject(resultStr);
                                                int resultCode = extJson.getIntValue("code");
                                                if (resultCode == Smile2PayResponse.CODE_SUCCESS) {
                                                    //刷脸成功
                                                    mSessionId = extJson.getString("sessionId");
                                                    mTradeNo = extJson.getString("tradeNo");
                                                    ftoken = extJson.getString("ftoken");
                                                    String alipayUid = extJson.getString("alipayUid");
                                                    System.out.println("接收：" + ftoken + "\nUUID" + alipayUid);

                                                    PaymentAPI api = APIManager.getInstance().getPaymentAPI();
                                                    String terminal_params = api.signWithDelegated(ftoken);

                                                    System.out.println("terminal_paramss:" + terminal_params);

                                                    PayModel payModel = new PayModel();
                                                    payModel.setProductCartModelList(ProductConst.getInstance().getProductCartModelList());
                                                    payModel.setPayWay(1);
                                                    payModel.setDeviceId(SystemUtils.getSerialNumber());
                                                    payModel.setFaceToken(ftoken);
                                                    payModel.setAliUid(alipayUid);
                                                    payModel.setUserId(SysConstConfig.getInstance().getUser());
                                                    payModel.setTerminal_params(terminal_params);
                                                    payModel.setOrders(orders);

                                                    RequestUtils.facePay(mContext, JSONObject.toJSONString(payModel), new MyObserverRes<JSONObject>(mContext) {
                                                        @Override
                                                        public void onSuccess(JSONObject result) {
                                                            if (mdDisposable != null && !mdDisposable.isDisposed()) {
                                                                mdDisposable.dispose();
                                                                mdDisposable = null;
                                                            }
                                                            if (SysConstConfig.getInstance().isSuccessClose()) {
                                                                showAutoClose(SysConstConfig.getInstance().getSuccessCloseSec());
                                                            }
                                                            if (result.getBoolean("success")) {
                                                                stateTv.setText("支付成功");
                                                                cardInfoLinear.setVisibility(View.VISIBLE);
                                                                JSONObject fk = result.getJSONObject("fk");
                                                                cardNoTv.setText("卡号：" + fk.getString("cardno"));
                                                                nameTv.setText("姓名：" + fk.getString("name"));
                                                                btyeTv.setText("补贴余额：" + fk.getString("btye"));
                                                                kyeTv.setText("自购余额：" + fk.getString("kye"));
                                                                tv_price.setText(result.getString("amount"));
                                                                selectPayPre.showCardInfo(fk);
                                                                selectPayPre.setAmount(result.getString("amount"));
                                                                prints(result.getString("orders"),result.getString("posnum"),4);
                                                                goFacePayResultSuccess(result, ftoken);
                                                            }else {

                                                                if (SysConstConfig.getInstance().isErrorClose()) {
                                                                    showAutoClose(SysConstConfig.getInstance().getErrorCloseSec());
                                                                }
                                                                stateTv.setText(result.getString("msg"));
                                                                selectPayPre.showError(result.getString("msg"));
                                                                if (SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.ali ||
                                                                        SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.jeBaoAli) {
                                                                    aliRead.goCardPayResultError(result.getString("msg"));
                                                                }
                                                            }

                                                        }

                                                        @Override
                                                        public void onFailure(Throwable e, String errorMsg) {
                                                            if (SysConstConfig.getInstance().isErrorClose()) {
                                                                showAutoClose(SysConstConfig.getInstance().getErrorCloseSec());
                                                            }
                                                            stateTv.setText(errorMsg);
                                                            selectPayPre.showError(errorMsg);
                                                            if (SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.ali ||
                                                                    SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.jeBaoAli) {
                                                                aliRead.goCardPayResultError(errorMsg);
                                                            }
                                                        }
                                                    });


//                                                    JSONObject params = new JSONObject();
//                                                    params.put("deviceId", SystemUtils.getSerialNumber());
//                                                    params.put("productCartModelList", SystemUtils.getSerialNumber());
//                                                    payModel.setProductCartModelList(ProductConst.getInstance().getProductCartModelList());
//                                                    params.put("faceToken", ftoken);
//                                                    params.put("aliUid", alipayUid);
//                                                    params.put("terminal_params", terminal_params);

                                                    //处理支付结果
//                                                    handleGoPayResult(mSessionId, mTradeNo, ftoken);
                                                } else {
                                                    // 刷脸失败处理
                                                    String subCode = extJson.getString("subCode");
                                                    String subMessage = extJson.getString("subMessage");
                                                    Log.e(TAG, "startVerify fail result : code = " + resultCode + ",subCode = " + subCode + ",subMessage = " + subMessage);
                                                    if ("Z6003".equals(subCode) || "Z6002".equals(subCode)) {
                                                        finish();
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {
                                Log.w(TAG, "response.getCode:" + response.getCode());
                            }
                        }

                        @Override
                        public void onEvent(String eventId, String data, Bundle extra) {
                            Log.i(TAG, "onEvent eventId:" + eventId + ",data:" + data);
                            JSONObject response = JSON.parseObject(data);
                            String eventType = response.getString("messageType");
                            JSONObject content = JSON.parseObject(response.getString("messageContent"));
                            Log.i("onEvent, content: ", content.toString());
                            if (eventType.equals("SMILE_NEW_SESSION")) { // 每次刷脸都会将当次的sessionId和tradeNo通过onEvent回调过来
                                mSessionId = content.getString("sessionId");
                                mTradeNo = content.getString("tradeNo");
                                Log.d(TAG, "sessionId== " + mSessionId + ".." + "tradeNo==" + mTradeNo);
                            }
                        }
                    });
        }


        if (SysConstConfig.getInstance().isAllowCard()) {
            if(SysConstConfig.getInstance().getPeripheralDeviceModel() == PeripheralDeviceEmus.defaultType) {
                CardReaderDevice.getInstance().initCardReader();
            }
        }
        if(SysConstConfig.getInstance().getSurfaceModel() != ModelEmus.fixedType) {
            mdDisposable = Flowable.intervalRange(0, closeSec, 0, 1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).doOnNext((aLong -> {
                String btnText = (closeSec - aLong) + "秒";
                if(preCloseTv != null) {
                    preCloseTv.setText(btnText);
                }
                tv_close_time.setText(btnText);
                String cardNo = CardReaderDevice.getInstance().readCardNo();
                cardNoPay(cardNo);
            })).doOnComplete(this::finish).subscribe();
        } else {
            new Thread(() -> {
                while(running) {
                    String cardNo = CardReaderDevice.getInstance().readCardNo();
                    runOnUiThread(() -> cardNoPay(cardNo));
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }).start();
        }
        cancelBut = findViewById(R.id.cancelBut);
        cancelBut.setOnClickListener(view -> {
            ProductConst.getInstance().setProductCartModelList(new ArrayList<>());
            EventBus.getDefault().post(new CartEvent());
            finish();
        });

        cashPayBut = findViewById(R.id.cashPayBut);
        cashPayBut.setOnClickListener(view -> {
            if (payStatus != 0) {
                Toast.makeText(mContext, "该订单已支付或者支付中", Toast.LENGTH_SHORT).show();

                return;
            }
            PayModel payModel = new PayModel();
            payModel.setProductCartModelList(ProductConst.getInstance().getProductCartModelList());
            payModel.setPayWay(1);
            payModel.setDeviceId(SystemUtils.getSerialNumber());
            payModel.setFaceToken(ftoken);
            payModel.setUserId(SysConstConfig.getInstance().getUser());
            payModel.setOrders(orders);

            RequestUtils.onLineConsumeCash(mContext, JSONObject.toJSONString(payModel), new MyObserverRes<JSONObject>(mContext) {
                @Override
                public void onSuccess(JSONObject result) {
                    running = false;
                    payStatus = 1;
                    stateTv.setText("支付成功");
                    cardInfoLinear.setVisibility(View.VISIBLE);
                    JSONObject fk = result.getJSONObject("fk");
                    cardNoTv.setText(String.format("卡号：%s", fk.getString("cardno")));
                    nameTv.setText(String.format("姓名：%s", fk.getString("name")));
                    btyeTv.setText(String.format("补贴余额：%s", "0.00"));
                    kyeTv.setText(String.format("自购余额：%s", "0.00"));
                    tv_price.setText(result.getString("amount"));
                    selectPayPre.showCardInfo(fk);
                    selectPayPre.setAmount(result.getString("amount"));
                    VoicePlay.with(mContext).writeSuccess();
                    prints(result.getString("orders"), result.getString("posnum"), 2);
                    ProductConst.getInstance().setProductCartModelList(new ArrayList<>());
                    EventBus.getDefault().post(new CartEvent());
                    if (SysConstConfig.getInstance().isSuccessClose()) {
                        showAutoClose(SysConstConfig.getInstance().getSuccessCloseSec());
                    }
                    /*if(SysConstConfig.getInstance().getSurfaceModel() != ModelEmus.fixedType) {
                        ProductConst.getInstance().setProductCartModelList(new ArrayList<>());
                        finish();
                    }*/
                }

                @Override
                public void onFailure(Throwable e, String errorMsg) {
                    payStatus = 0;
                }
            });
        });
        if (SysConstConfig.getInstance().isAllowCash()) {
            cashPayBut.setVisibility(View.VISIBLE);
        } else {
            cashPayBut.setVisibility(View.GONE);
        }
    }

    private void startKeyScan(){
        System.out.println("云设备");
        scanKeyManager = new ScanKeyManager((String value) -> {
            if (payStatus != 0) {
                Toast.makeText(mContext, "该订单已支付或者支付中", Toast.LENGTH_SHORT).show();
                return;
            }
            Log.i("MainActivity", "ScanValue->" + value);
            payStatus = 1;
            try {
                if (value.length() < 10) {
                    cardNoPay(value);
                } else {
                    onPay(value);
                }
            } catch (Exception e) {
                e.printStackTrace();
                payStatus = 0;
            }
        });
    }

    public void goFacePayResultSuccess(JSONObject reqJson, String ftoken) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sessionId", mSessionId);
        jsonObject.put("ftoken", ftoken);
        jsonObject.put("tradeNo", mTradeNo);
        jsonObject.put("success", true); // 必填，false为支付失败
        jsonObject.put("resultTimeOut", 3); //倒计时
        JSONObject outerSummary = new JSONObject();
        outerSummary.put("enablePaymentVoice", true);
        outerSummary.put("actualAmount", reqJson.getString("amount"));
        outerSummary.put("title", reqJson.getString("msg"));
        JSONObject advancedConfig = new JSONObject();
        advancedConfig.put("version", "2.0");
        advancedConfig.put("OuterSummary", outerSummary);
        advancedConfig.put("OuterExtends", reqJson.getJSONArray("outerExtends"));
        jsonObject.put("advancedConfig", advancedConfig.toJSONString());
        Bundle bundle = new Bundle();
        bundle.putString("templateId", SystemConfig.getInstance().getTemplateId());
        bundle.putString("operateType", "showScanFaceOfflinePayResult");// 刷卡/扫码都使用这个operateType
        bundle.putString("page", "payResult");
        bundle.putString("templateParams", jsonObject.toJSONString());
        BPaaSApi.getInstance().startBPaaSService(SystemConfig.getInstance().getAbcpApplicationAppid(),
                SystemConfig.getInstance().getTemplateServiceCode(), bundle, new BPaaSCallback() {
                    @Override
                    public void onResponse(BPaaSResponse response) {
                        AliRead aliRead = new AliRead();
                        aliRead.responseInvoke(response, "showScanCardOfflinePayResult");
                        ProductConst.getInstance().setProductCartModelList(new ArrayList<>());
                        EventBus.getDefault().post(new CartEvent());
                    }

                    @Override
                    public void onEvent(String eventId, String data, Bundle extra) {
                        Log.i(TAG, "onEvent eventId:" + eventId + ",data:" + data);
                        JSONObject response = JSON.parseObject(data);
                        if (response != null) {
                            String eventType = response.getString("messageType");
                            if (eventType.equals("CLOSE")) {
                                //支付结果页已关闭
                                Log.i(TAG, "刷卡支付结果页已关闭");
                            } else if (eventType.equals("ShowSuccess")) {
                                //支付结果页展示成功
                                Log.i(TAG, "刷卡支付结果页展示成功");
                                ProductConst.getInstance().setProductCartModelList(new ArrayList<>());
                                EventBus.getDefault().post(new CartEvent());
                            } else if (eventType.equals("ShowFail")) {
                                //支付结果页展示失败
                                Log.i(TAG, "刷卡支付结果页展示失败");
                            }

                        }
                    }
                });
    }

    public static final byte[] FY_CARD_PWS = {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff};

    private void cardNoPay(String cardNo) {
        if (StringUtils.isEmpty(cardNo)) {
            return;
        }
        try {
            /*if (!SystemUtils.checkCard(mContext, cardNo)) {
                return;
            }*/
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (SysConstConfig.getInstance().getReadCardType() == ReadCardTypeEmus.cardSQ) {
            byte[] bReturn = CardReaderDevice.getInstance().readM1CardChunkData(0, 0, FY_CARD_PWS);
            if (bReturn != null) {
                Log.e(TAG, "bReturn " + (SysConstConfig.getInstance().getCardDataSector() * 4) + " length " + bReturn.length + " " + CardReaderUtils.byteArray2HexString(bReturn));
//                    str +=  CardReaderUtils.byteArray2HexString(bReturn) + "\n";
            } else {
                System.out.println("方式为空");
            }
        }

        payStatus = 1;
        if (SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.ali || SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.jeBaoAli) {

            aliRead.showScanCardPayResult(type -> {
                System.out.println("支付宝组件交易：");
                try {
                    stateTv.setText("支付中");
                    if(selectPayPre != null) {
                        selectPayPre.showError("支付中");
                    }
                    onPay(cardNo);
                } catch (Exception e) {
                    e.printStackTrace();
                    payStatus = 0;
                }
            });
        } else {
            try {
                stateTv.setText("支付中");
                if(selectPayPre != null) {
                    selectPayPre.showError("支付中");
                }
                onPay(cardNo);
            } catch (Exception e) {
                e.printStackTrace();
                payStatus = 0;
            }
        }
    }

    @Override
    protected void initData() {
        defaultCartAdapter = new DefaultCartPreAdapter(mContext);
        LinearLayoutManager layoutManager2 = new LinearLayoutManager(mContext);
        cartRv.setLayoutManager(layoutManager2);
        cartRv.setAdapter(defaultCartAdapter);
        tv_price.setText("￥" + ProductConst.getInstance().getProductCartPrice());


    }

    @Override
    protected void dissmissPresnetation() {
        if (selectPayPre != null) {
            selectPayPre.dismiss();
        }
    }


    @Override
    public void initPresentation() {
        super.initPresentation();
        if (mDisplay != null) {
            selectPayPre = new SelectPayPre(SelectPayActivity.this, mDisplay);
            registerPresentation(selectPayPre);
            showPresentation(selectPayPre);
            if(selectPayPre != null) {
                selectPayPre.show();
            }
        }
        if(selectPayPre != null) {
            preCloseTv = selectPayPre.getTv_close_time();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        running = false;
        if (mdDisposable != null && !mdDisposable.isDisposed()) {
            mdDisposable.dispose();
            mdDisposable = null;
        }
        if (scanner != null) {
            scanner.stopScan();
            scanner = null;
        }
    }

    private void onPay(String cardNo) {
        if(cardNo.length() < 10) { //确认为cardSn
            if(SysConstConfig.getInstance().getOfflineGetCardSnType() == OfflineGetCardSnTypeEmus.reverse) {
                byte[] cardSnTemp = ByteUtil.hexStringToByte(cardNo.toUpperCase());
                byte[] cardSn = new byte[4];
                for (int i = 0; i < cardSnTemp.length; i++) {
                    cardSn[i] = cardSnTemp[3 - i];
                }
                stateTv.setText("支付中");
                if(selectPayPre != null) {
                    selectPayPre.showError("支付中");
                }
                cardNo = ByteUtil.bytesToHexString(cardSn).toUpperCase();
            }
        }
        if (mdDisposable != null && !mdDisposable.isDisposed()) {
            mdDisposable.dispose();
            mdDisposable = null;
        }
        if(SysConstConfig.getInstance().getSurfaceModel() != ModelEmus.fixedType) {
            mdDisposable = Flowable.intervalRange(0, 15, 0, 1, TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread()).doOnNext((aLong -> {
                        String btnText = (15 - aLong) + "秒";
                        if(preCloseTv != null) {
                            preCloseTv.setText(btnText);
                        }
                        tv_close_time.setText(btnText);
                    })).doOnComplete(this::finish).subscribe();
        }
        //组合数据
        SharedPreferences systemI = getSharedPreferences("systemI", MODE_PRIVATE);
        PayModel payModel = new PayModel();
        payModel.setAuth(cardNo);
        payModel.setProductCartModelList(ProductConst.getInstance().getProductCartModelList());
        payModel.setPayWay(1);
        payModel.setDeviceId(SystemUtils.getSerialNumber());
        payModel.setUserId(SysConstConfig.getInstance().getUser());
        payModel.setOrders(orders);

        //检测是否脱机消费
        if (SysConstConfig.getInstance().isOnLinePay()) {
            //脱机消费流程
            if (mdDisposable != null && !mdDisposable.isDisposed()) {
                mdDisposable.dispose();
                mdDisposable = null;
            }
            FkEntity fkEntity = fkEntityDao.queryBuilder().where(FkEntityDao.Properties.Cardsn.eq(cardNo.toUpperCase())).unique();
            if (fkEntity == null) {
                if (mdDisposable != null && !mdDisposable.isDisposed()) {
                    mdDisposable.dispose();
                    mdDisposable = null;
                }
                if (SysConstConfig.getInstance().isErrorClose()) {
                    showAutoClose(SysConstConfig.getInstance().getErrorCloseSec());
                }
                stateTv.setText("未发卡");
                if(selectPayPre != null) {
                    selectPayPre.showError("未发卡");
                }
                return;
            }
            if(fkEntity.getIsGuaShi() == 1) {
                stateTv.setText("此卡已挂失");
                if(selectPayPre != null) {
                    selectPayPre.showError("此卡已挂失");
                }
                return;
            }
            String cartPrice = ProductConst.getInstance().getProductCartPrice();
            int sc = 1;
            if (new BigDecimal(fkEntity.getBtye()).compareTo(new BigDecimal(0)) <= 0 || new BigDecimal(fkEntity.getBtye()).compareTo(new BigDecimal(cartPrice)) < 0) {
                sc = 0;
                if (new BigDecimal(fkEntity.getKye()).compareTo(new BigDecimal(0)) <= 0 || new BigDecimal(fkEntity.getKye()).compareTo(new BigDecimal(cartPrice)) < 0) {
                    stateTv.setText("余额不足");
                    if(selectPayPre != null) {
                        selectPayPre.showError("余额不足");
                    }
                    return;
                }
            }

            if (fkEntity.getValiddate().compareTo(new Date()) < 0) {
                stateTv.setText("此卡已超过有效期");
                if(selectPayPre != null) {
                    selectPayPre.showError("此卡已超过有效期");
                }
                return;
            }
            if (SysConstConfig.getInstance().isSuccessClose()) {
                showAutoClose(SysConstConfig.getInstance().getSuccessCloseSec());
            }
            saveUnOnLine(fkEntity, systemI.getString("user", ""), sc);
            stateTv.setText("支付成功");
            cardInfoLinear.setVisibility(View.VISIBLE);
            cardNoTv.setText(String.format("卡号：%s", fkEntity.getCardno()));
            nameTv.setText(String.format("姓名：%s", fkEntity.getName()));
            btyeTv.setText("请注意");
            kyeTv.setText("当前为脱机记账模式");
            if(selectPayPre != null) {
                selectPayPre.showCardInfo(fkEntity);
            }
            ProductConst.getInstance().setProductCartModelList(new ArrayList<>());
            EventBus.getDefault().post(new CartEvent());
            VoicePlay.with(mContext).writeSuccess();
        } else {
            if (Looper.myLooper() == null) {
                Looper.prepare();
            }

            if (payModel.getAuth().length() >= 16 && KeyAdd.isNumeric(payModel.getAuth())
                    && !SystemUtils.isDecodeCard(payModel.getAuth())
                    && APIManager.getInstance().getDeviceAPI().getDeviceSn() != null) {
                aliRead.showScanCardPayResult(type -> {
                    System.out.println("支付宝组件交易22：");
                    RequestUtils.onLineConsume(mContext, JSONObject.toJSONString(payModel), new MyObserverRes<>(mContext) {
                        @Override
                        public void onSuccess(JSONObject result) {
                            if (mdDisposable != null && !mdDisposable.isDisposed()) {
                                mdDisposable.dispose();
                                mdDisposable = null;
                            }
                            String wxPayCode = result.getString("wxPayStatus");
                            if ("USERPAYING".equals(wxPayCode)) {
                                payingDialog.show();
                                payingDialog.setMsg("请输入密码");
                                checkWxOrder(result);
                                return;
                            }

                            if (SysConstConfig.getInstance().isSuccessClose()) {
                                showAutoClose(SysConstConfig.getInstance().getSuccessCloseSec());
                            }
                            stateTv.setText("支付成功");
                            cardInfoLinear.setVisibility(View.VISIBLE);
                            JSONObject fk = result.getJSONObject("fk");
                            cardNoTv.setText(String.format("卡号：%s", fk.getString("cardno")));
                            nameTv.setText(String.format("姓名：%s", fk.getString("name")));
                            btyeTv.setText(String.format("补贴余额：%s", fk.getString("btye")));
                            kyeTv.setText(String.format("自购余额：%s", fk.getString("kye")));
                            tv_price.setText(result.getString("amount"));
                            if(selectPayPre != null) {
                                selectPayPre.showCardInfo(fk);
                                selectPayPre.setAmount(result.getString("amount"));
                            }
                            prints(result.getString("orders"), result.getString("posnum"), 3);
                            ProductConst.getInstance().setProductCartModelList(new ArrayList<>());
                            EventBus.getDefault().post(new CartEvent());
                            if (SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.ali ||
                                    SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.jeBaoAli) {
                                aliRead.goCardPayResultSuccess(result);
                            } else {
                                VoicePlay.with(mContext).writeSuccess();
                            }
                        }

                        @Override
                        public void onFailure(Throwable e, String errorMsg) {
                            payStatus = 0;
                            if (mdDisposable != null && !mdDisposable.isDisposed()) {
                                mdDisposable.dispose();
                                mdDisposable = null;
                            }
                            if (SysConstConfig.getInstance().isErrorClose()) {
                                showAutoClose(SysConstConfig.getInstance().getErrorCloseSec());
                            }
                            stateTv.setText(errorMsg);
                            if(selectPayPre != null) {
                                selectPayPre.showError(errorMsg);
                            }
                            if (SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.ali ||
                                    SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.jeBaoAli) {
                                aliRead.goCardPayResultError(errorMsg);
                            }


                        }
                    });
                });

            } else {
                RequestUtils.onLineConsume(mContext, JSONObject.toJSONString(payModel), new MyObserverRes<>(mContext, false) {
                    @Override
                    public void onSuccess(JSONObject result) {
                        if (mdDisposable != null && !mdDisposable.isDisposed()) {
                            mdDisposable.dispose();
                            mdDisposable = null;
                        }
                        running = false;
                        String wxPayCode = result.getString("wxPayStatus");
                        if ("USERPAYING".equals(wxPayCode)) {
                            payingDialog.show();
                            payingDialog.setMsg("请输入密码");
                            checkWxOrder(result);
                            return;
                        }

                        if (SysConstConfig.getInstance().isSuccessClose()) {
                            showAutoClose(SysConstConfig.getInstance().getSuccessCloseSec());
                        }
                        stateTv.setText("支付成功");
                        cardInfoLinear.setVisibility(View.VISIBLE);
                        JSONObject fk = result.getJSONObject("fk");
                        cardNoTv.setText(String.format("卡号：%s", fk.getString("cardno")));
                        nameTv.setText(String.format("姓名：%s", fk.getString("name")));
                        btyeTv.setText(String.format("补贴余额：%s", fk.getString("btye")));
                        kyeTv.setText(String.format("自购余额：%s", fk.getString("kye")));
                        tv_price.setText(result.getString("amount"));
                        if(selectPayPre != null) {
                            selectPayPre.showCardInfo(fk);
                            selectPayPre.setAmount(result.getString("amount"));
                        }
                        if (payModel.getAuth().length() == 18) {
                            prints(result.getString("orders"), result.getString("posnum"), 3);
                        }else {
                            prints(result.getString("orders"), result.getString("posnum"), 0);
                        }
                        if(SysConstConfig.getInstance().getSurfaceModel() != ModelEmus.fixedType) {
                            ProductConst.getInstance().setProductCartModelList(new ArrayList<>());
                            EventBus.getDefault().post(new CartEvent());
                        }
                        if (SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.ali ||
                                SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.jeBaoAli) {
                            aliRead.goCardPayResultSuccess(result);
                        } else {
                            VoicePlay.with(mContext).writeSuccess();
                        }
                    }

                    @Override
                    public void onFailure(Throwable e, String errorMsg) {
                        if(e != null && e.getCause() != null) {
                            if(e.getCause().toString().contains("java.net.ConnectException")) {
                                errorMsg = "网络异常,请切换离线模式消费";
                            }
                        }
                        if (mdDisposable != null && !mdDisposable.isDisposed()) {
                            mdDisposable.dispose();
                            mdDisposable = null;
                        }
                        if (SysConstConfig.getInstance().isErrorClose()) {
                            showAutoClose(SysConstConfig.getInstance().getErrorCloseSec());
                        }
                        stateTv.setText(errorMsg);
                        if(selectPayPre != null) {
                            selectPayPre.showError(errorMsg);
                        }
                        if (SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.ali ||
                                SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.jeBaoAli) {
                            aliRead.goCardPayResultError(errorMsg);
                        }
                    }
                });
            }

        }
    }

    private void showAutoClose(int sec) {
        if(SysConstConfig.getInstance().getSurfaceModel() != ModelEmus.fixedType) {
            mdDisposable = Flowable.intervalRange(0, sec, 0, 1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).doOnNext((aLong -> {
                String btnText = (sec - aLong) + "秒";
                if(preCloseTv != null) {
                    preCloseTv.setText(btnText);
                }
                tv_close_time.setText(btnText);
            })).doOnComplete(this::finish).subscribe();
        } else {
            closeText.setVisibility(View.VISIBLE);
            mdDisposable = Flowable.intervalRange(0, sec, 0, 1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).doOnNext((aLong -> {
                String btnText = (sec - aLong) + "秒";
                if(preCloseTv != null) {
                    preCloseTv.setText(btnText);
                }
                tv_close_time.setText(btnText);
            })).doOnComplete(() -> {
                if(SysConstConfig.getInstance().isFixedAutoPay()) {
                    Intent intent = getIntent();
                    finish();
                    startActivity(intent);
                } else {
                    finish();
                }
            }).subscribe();
        }
    }

    public static void prints(String orders, String posnum, int sc) {
        try {
            PrintUtil pUtil = new PrintUtil();

            // 店铺名 居中 放大
            pUtil.printAlignment(1);
            pUtil.setTextSize(SysConstConfig.getInstance().getPrintTextSize());
            pUtil.printLargeText("膳食订餐系统");
            pUtil.printLine();
            pUtil.printAlignment(0);
            pUtil.printLine();
            pUtil.setTextSize(SysConstConfig.getInstance().getPrintTextSize());
            pUtil.printTwoColumn("机器号：", posnum);
            pUtil.printLine();
            pUtil.printTwoColumn("订单号:", orders);
            pUtil.printLine();
            pUtil.printTwoColumn("下单时间:", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            pUtil.printLine();
            pUtil.setTextSize(0);
            // 分隔线
            pUtil.printDashLine();
            pUtil.printLine();
            //打印商品列表
            pUtil.setTextSize(SysConstConfig.getInstance().getPrintTextSize());
            pUtil.printThreeColumn("商品", "数量", "小计");
            pUtil.printLine();
//            for (Foods goo : threePrintVo.getFoods()) {
//                pUtil.printThreeColumn(goo.getDinnerName().trim() + " ", goo.getName(), "x" + String.valueOf(goo.getNum()), "￥"+String.valueOf(goo.getAmount()));
//            }
//            pUtil.printDashLine();

            for (ProductCartModel goo : ProductConst.getInstance().getProductCartModelList()) {
                BigDecimal amount = new BigDecimal(goo.getNumber())
                        .multiply(new BigDecimal(goo.getPrice()))
                        .setScale(2, RoundingMode.DOWN);
                pUtil.printThreeColumn(goo.getName(), String.valueOf(goo.getNumber()), amount.toString());
                pUtil.printLine();
            }
            pUtil.setTextSize(0);
            pUtil.printDashLine();
            pUtil.setTextSize(SysConstConfig.getInstance().getPrintTextSize());
            pUtil.printLine();
            pUtil.printTwoColumn("合计金额:", ProductConst.getInstance().getProductCartPrice());
            pUtil.printLine();
            switch (sc) {
                case 0:
                case 1:
                    pUtil.printTwoColumn("消费方式:", "IC卡支付");
                    break;
                case 2:
                    pUtil.printTwoColumn("消费方式:", "现金支付");
                    break;
                case 3:
                    pUtil.printTwoColumn("消费方式:", "微信支付");
                    break;
            }
            pUtil.printLine();
            pUtil.printLargeText("小票仅限当日当餐有效");
            pUtil.printLine();
            pUtil.setTextSize(0);
            pUtil.printDashLine();
            pUtil.printLine(4);
            pUtil.printQZ();
            if (!MainActivity.ISCONNECT || MainActivity.myBinder == null) {
                System.out.println("没有驱动，退出");
                return;
            }
            if (MainActivity.ISCONNECT) {
                MainActivity.myBinder.Write(pUtil.getOutbyte(), new TaskCallback() {
                    @Override
                    public void OnSucceed() {

                    }

                    @Override
                    public void OnFailed() {

                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveUnOnLine(FkEntity fkEntity, String userId, Integer sc) {
        BigDecimal price = new BigDecimal(0);
        List<OrdersDetailsEntity> ordersDetailsEntityList = new ArrayList<>();
        for (ProductCartModel goo : ProductConst.getInstance().getProductCartModelList()) {
            OrdersDetailsEntity ordersDetailsEntity = new OrdersDetailsEntity();
            ordersDetailsEntity.setOrders(orders);
            ordersDetailsEntity.setBm(goo.getBm());
            ordersDetailsEntity.setDinner(goo.getDinner());
            ordersDetailsEntity.setNumber(goo.getNumber());
            ordersDetailsEntity.setName(goo.getName());
            ordersDetailsEntity.setAddr(goo.getAddr());
            ordersDetailsEntity.setPrice(goo.getPrice());
            ordersDetailsEntity.setZl(goo.getZl());
            ordersDetailsEntityList.add(ordersDetailsEntity);
            price = price.add(new BigDecimal(goo.getPrice()));
        }
        OrdersEntity ordersEntity = new OrdersEntity();
        ordersEntity.setOrders(orders);
        ordersEntity.setName(fkEntity.getName());
        ordersEntity.setCardsn(fkEntity.getCardsn());
        ordersEntity.setType(sc);
        ordersEntity.setAmountPrice(price.toPlainString());
        ordersEntity.setDeviceId(SystemUtils.getSerialNumber());
        ordersEntity.setCreateTime(new Date());
        ordersEntity.setUserId(userId);
        ordersEntityDao.insert(ordersEntity);
        ordersDetailsEntityDao.insertInTx(ordersDetailsEntityList);
        BigDecimal kye = new BigDecimal(fkEntity.getKye());
        BigDecimal btYe = new BigDecimal(fkEntity.getBtye());
        if(price.compareTo(btYe) >= 0) {
            price = price.subtract(btYe);
            btYe = new BigDecimal(0);
        } else {
            btYe = btYe.subtract(price);
            price = new BigDecimal(0);
        }
        if(price.compareTo(new BigDecimal(0)) > 0) {
            kye = kye.subtract(price);
        }
        fkEntity.setKye(kye.toPlainString());
        fkEntity.setBtye(btYe.toPlainString());
        fkEntityDao.update(fkEntity);
    }


    private OnDecodeCallback callback = new OnDecodeCallback() {
        @Override
        public void onDecode(final String code) {
            Log.e("TAG", "onDecode_ = " + code + " code length " + code.length());
            String codeTrim = code.trim();
            Log.e("TAG", "codeTrim = " + codeTrim + " code length " + codeTrim.length());
            if (payStatus != 0) {
                runOnUiThread(() -> Toast.makeText(mContext, "该订单已支付或者支付中", Toast.LENGTH_SHORT).show());
                return;
            }
            payStatus = 1;
            if (SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.ali || SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.jeBaoAli) {
                aliRead.showScanCardPayResult(type -> {
                    try {
                        onPay(code);
                    } catch (Exception e) {
                        payStatus = 0;
                    }
                });
            } else {
                try {
                    onPay(code);
                } catch (Exception e) {
                    payStatus = 0;
                }
            }
        }
    };


    @Override
    protected void onPause() {
        if (aliRead != null) {
            aliRead.close(type -> {

            });
        }
        super.onPause();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if(event.getKeyCode() == KeyEvent.KEYCODE_F3 && event.getAction() == KeyEvent.ACTION_DOWN) {
            cancelBut.performClick();
            return true;
        }
        /*if(event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN)  {
            if (cashPayBut.getVisibility() == View.VISIBLE) {
                cashPayBut.performClick();
                return true;
            }
        }*/
        if (event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
            if(scanKeyManager != null) {
                scanKeyManager.analysisKeyEvent(event);
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    private void checkWxOrder(JSONObject jsonObject) {
        mdDisposable = Flowable.intervalRange(0, 15, 0, 1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).doOnNext((aLong -> {
            String btnText = (15 - aLong) + "秒";
            if(preCloseTv != null) {
                preCloseTv.setText(btnText);
            }
            tv_close_time.setText(btnText);
            System.out.println("查询订单");

            RequestUtils.checkOrder(mContext, jsonObject.toJSONString(), new MyObserverRes<JSONObject>(mContext, false) {
                @Override
                public void onSuccess(JSONObject result) {
                    String wxPayCode = result.getString("wxPayStatus");
                    if ("SUCCESS".equals(wxPayCode)) {
                        payingDialog.hide();
                        if (mdDisposable != null && !mdDisposable.isDisposed()) {
                            mdDisposable.dispose();
                            mdDisposable = null;
                        }
                        if (SysConstConfig.getInstance().isSuccessClose()) {
                            showAutoClose(SysConstConfig.getInstance().getSuccessCloseSec());
                        }
                        stateTv.setText("支付成功");
                        cardInfoLinear.setVisibility(View.VISIBLE);
                        JSONObject fk = result.getJSONObject("fk");
                        cardNoTv.setText("卡号：" + fk.getString("cardno"));
                        nameTv.setText("姓名：" + fk.getString("name"));
                        btyeTv.setText("补贴余额：" + fk.getString("btye"));
                        kyeTv.setText("自购余额：" + fk.getString("kye"));
                        if(selectPayPre != null) {
                            selectPayPre.showCardInfo(fk);
                        }
                        prints(result.getString("orders"), result.getString("posnum"), 3);
                        ProductConst.getInstance().setProductCartModelList(new ArrayList<>());
                        EventBus.getDefault().post(new CartEvent());
                        if (SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.ali || SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.jeBaoAli) {
                            aliRead.goCardPayResultSuccess(result);
                        } else {
                            VoicePlay.with(mContext).writeSuccess();
                        }

                    } else if ("ERROR".equals(wxPayCode)) {
                        if (mdDisposable != null && !mdDisposable.isDisposed()) {
                            mdDisposable.dispose();
                            mdDisposable = null;
                        }
                        if (SysConstConfig.getInstance().isErrorClose()) {
                            showAutoClose(SysConstConfig.getInstance().getErrorCloseSec());
                        }
                        stateTv.setText("支付失败");
                        if(selectPayPre != null) {
                            selectPayPre.showError("支付失败");
                        }
                        if (SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.ali || SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.jeBaoAli) {
                            aliRead.goCardPayResultError("支付失败");
                        }
                        payStatus = 0;
                        payingDialog.hide();
                    }
                }

                @Override
                public void onFailure(Throwable e, String errorMsg) {
                    if (mdDisposable != null && !mdDisposable.isDisposed()) {
                        mdDisposable.dispose();
                        mdDisposable = null;
                    }
                    if (SysConstConfig.getInstance().isErrorClose()) {
                        showAutoClose(SysConstConfig.getInstance().getErrorCloseSec());
                    }
                    stateTv.setText(errorMsg);
                    if(selectPayPre != null) {
                        selectPayPre.showError(errorMsg);
                    }
                    if (SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.ali || SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.jeBaoAli) {
                        aliRead.goCardPayResultError(errorMsg);
                    }
                    payingDialog.hide();
                }
            });

        })).doOnComplete(() -> RequestUtils.closeOrder(mContext, jsonObject.toJSONString(), new MyObserverRes<JSONObject>(mContext, false) {
            @Override
            public void onSuccess(JSONObject result) {
                String wxPayCode = result.getString("wxPayStatus");
                if ("SUCCESS".equals(wxPayCode)) {
                    payingDialog.hide();
                    if (mdDisposable != null && !mdDisposable.isDisposed()) {
                        mdDisposable.dispose();
                        mdDisposable = null;
                    }
                    if (SysConstConfig.getInstance().isSuccessClose()) {
                        showAutoClose(SysConstConfig.getInstance().getSuccessCloseSec());
                    }
                    cardInfoLinear.setVisibility(View.VISIBLE);
                    stateTv.setText("订单支付超时,已关闭;请重新发起支付");
                    if(selectPayPre != null) {
                        selectPayPre.showError("订单支付超时,已关闭;请重新发起支付");
                    }
                    ProductConst.getInstance().setProductCartModelList(new ArrayList<>());
                    EventBus.getDefault().post(new CartEvent());
                } else if ("ERROR".equals(wxPayCode)) {
                    if (mdDisposable != null && !mdDisposable.isDisposed()) {
                        mdDisposable.dispose();
                        mdDisposable = null;
                    }
                    if (SysConstConfig.getInstance().isErrorClose()) {
                        showAutoClose(SysConstConfig.getInstance().getErrorCloseSec());
                    }
                    stateTv.setText("关闭订单失败");
                    if(selectPayPre != null) {
                        selectPayPre.showError("关闭订单失败");
                    }
                    if (SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.ali || SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.jeBaoAli) {
                        aliRead.goCardPayResultError("关闭订单失败");
                    }
                    payStatus = 0;
                    payingDialog.hide();
                }
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                payingDialog.hide();
                if (mdDisposable != null && !mdDisposable.isDisposed()) {
                    mdDisposable.dispose();
                    mdDisposable = null;
                }
                if (SysConstConfig.getInstance().isErrorClose()) {
                    showAutoClose(SysConstConfig.getInstance().getErrorCloseSec());
                }
                stateTv.setText(errorMsg);
                if(selectPayPre != null) {
                    selectPayPre.showError(errorMsg);
                }
                if (SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.ali || SystemConfig.getInstance().getDeviceType() == DeviceTypeEmus.jeBaoAli) {
                    aliRead.goCardPayResultError(errorMsg);
                }
            }
        })).subscribe();
    }
}

